package com.yuntu.controller;

import com.yuntu.pojo.User;
import com.yuntu.service.UserService;
import com.yuntu.utils.PageUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
@RequestMapping("/login")
public class UserController {
    private Logger logger=Logger.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @RequestMapping(value = "/doLogin",method = RequestMethod.GET)
    public String doLogin(String devCode, String devPassword, HttpServletRequest request, HttpSession session) throws Exception{
        logger.debug("doLogin-------------");
        User user=userService.login(devCode,devPassword);
        if (user!=null){
            session.setAttribute("userSession",user);
            return "redirect:/login/getPage";
        }else {
            request.setAttribute("error","用户名或密码不正确");
            return "login";
        }
    }
    @RequestMapping(value = "/getPage",method = RequestMethod.GET)
    public String getPage(Integer pageIndex,HttpSession session) throws Exception{
        if (pageIndex==null){
            pageIndex=1;
        }
        PageUtil<User> pageUtil=new PageUtil<>();
        pageUtil.setPageindex(pageIndex);//第几页
        pageUtil.setPagesize(2);//一页显示几个
        userService.getPageAll(pageUtil);
        session.setAttribute("pageUtil",pageUtil);
        return "frame";
    }
    @RequestMapping(value = "/getAllById/{id}",method = RequestMethod.GET)
    public String getAllById(@PathVariable int id, Model model)throws Exception{
        User user=userService.getAllById(id);
        model.addAttribute(user);
        return "upd";
    }
    @RequestMapping(value = "/upd",method = RequestMethod.POST)
    public String upd(User user) throws Exception{
        logger.debug("============="+user.getId());
        if (userService.upd(user)){
            return  "redirect:/login/getPage";
        }
        return "upd";
    }
    @RequestMapping(value = "/del/{id}")
    public String del(@PathVariable int id)throws Exception{
        if (userService.del(id)){
            return  "redirect:/login/getPage";
        }
        return "frame";
    }
    @RequestMapping(value = "/add.do")
    public String addjsp(){
        return "add";
    }

    @RequestMapping(value = "/add")
    public String add(User user,HttpSession session)throws Exception{
        user.setCreationDate(new Date());
        user.setModifyDate(new Date());
        if (userService.add(user)){
            return "redirect:/login/getPage";
        }
        return "add";
    }
}
